package com.cskaoyan.wordmemorize.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cskaoyan.wordmemorize.common.constant.ResultCodeEnum;
import com.cskaoyan.wordmemorize.common.exception.BusinessException;
import com.cskaoyan.wordmemorize.converter.PayConverter;
import com.cskaoyan.wordmemorize.dao.entity.UserDO;
import com.cskaoyan.wordmemorize.dao.entity.UserVocBoundStatisticsDO;
import com.cskaoyan.wordmemorize.dao.entity.VocPaySaleDO;
import com.cskaoyan.wordmemorize.dao.mapper.UserMapper;
import com.cskaoyan.wordmemorize.dao.mapper.UserVocBoundStatisticsMapper;
import com.cskaoyan.wordmemorize.dao.mapper.VocPaySaleMapper;
import com.cskaoyan.wordmemorize.dto.admin.PageDTO;
import com.cskaoyan.wordmemorize.dto.app.PayOrderDTO;
import com.cskaoyan.wordmemorize.dto.app.UserDTO;
import com.cskaoyan.wordmemorize.dto.app.VocPaySaleDTO;
import com.cskaoyan.wordmemorize.request.PageRequest;
import com.cskaoyan.wordmemorize.request.PaySuccessNotifyCommand;
import com.cskaoyan.wordmemorize.request.VocPaySaleCommand;
import com.cskaoyan.wordmemorize.service.UserPayService;
import com.cskaoyan.wordmemorize.service.UserService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import java.time.LocalDate;
import java.util.List;

/**
 * @author Yan.z.h
 * @version 1.0
 */
@Service
public class UserPayServiceImpl implements UserPayService {
    @Resource
    UserService userService;
    @Resource
    PayConverter payConverter;
    @Resource
    VocPaySaleMapper vocPaySaleMapper;
    @Resource
    UserVocBoundStatisticsMapper userVocBoundStatisticsMapper;
    @Resource
    UserMapper userMapper;

    @Transactional
    @Override
    public PayOrderDTO pay(VocPaySaleCommand command, Long userId) {
        if (command == null) {
            return null;
        }
        if (command.getIsSignCard()) {
            UserDTO userInfo = userService.getUserInfo(userId);
            if (userInfo.getHasSignCard() == 1) {
                throw new BusinessException(ResultCodeEnum.USER_ALREADY_OWN_RESIGN_CARD);
            }
        }
        VocPaySaleDO converterVocPaySaleDO = payConverter.vocPaySaleCommand2DO(command);
        converterVocPaySaleDO.setUserId(userId);
        //插入到数据库
//        LambdaQueryWrapper<VocPaySaleDO> vocPaySaleDOLambdaQueryWrapper = new LambdaQueryWrapper<>();
//        vocPaySaleDOLambdaQueryWrapper.eq(VocPaySaleDO::getId, converterVocPaySaleDO.getId());
//        VocPaySaleDO selectVocPaySaleDO = vocPaySaleMapper.selectOne(vocPaySaleDOLambdaQueryWrapper);
//        if (selectVocPaySaleDO !=null)
//        {
//            return  null;
//        }
        converterVocPaySaleDO.setStatus(1);
        vocPaySaleMapper.insert(converterVocPaySaleDO);
        System.out.println("回填id " + converterVocPaySaleDO.getId());
        //请求支付
        HttpClient client = HttpClient.newHttpClient();
        String paymentGatewayUrl = "https://www.baidu.com/";

        // 创建请求体
        String jsonBody = String.format("{\"id\":%s,\"userid\":%s,\"total\":%f}", command.getId(),
                command.getUserId(), command.getPayPrice().doubleValue());

        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(paymentGatewayUrl))
                .timeout(Duration.ofSeconds(10))
                .header("Content-Type", "application/json")
                .POST(HttpRequest.BodyPublishers.ofString(jsonBody))
                .build();

        //发送请求并获得请求
        try {
            HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        //成功返回

        PayOrderDTO payOrderDTO = new PayOrderDTO();
        payOrderDTO.setId(String.valueOf(converterVocPaySaleDO.getId()));
        payOrderDTO.setTotalAmount(converterVocPaySaleDO.getPayPrice());
        payOrderDTO.setSubject(converterVocPaySaleDO.getItemName());
        return payOrderDTO;


    }

    @Transactional
    @Override
    public String paySuccess(PaySuccessNotifyCommand command) {
        Long userId = command.getUserId();
        if ("TRADE_SUCCESS".equals(command.getTradeStatus())) {
            LambdaUpdateWrapper<VocPaySaleDO> vocPaySaleDOLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
            vocPaySaleDOLambdaUpdateWrapper.eq(VocPaySaleDO::getId, command.getId()).eq(VocPaySaleDO::getUserId, userId).set(VocPaySaleDO::getStatus, 2);
            vocPaySaleMapper.update(vocPaySaleDOLambdaUpdateWrapper);

            LambdaQueryWrapper<VocPaySaleDO> vocPaySaleDOLambdaQueryWrapper = new LambdaQueryWrapper<>();
            vocPaySaleDOLambdaQueryWrapper.eq(VocPaySaleDO::getId, command.getId()).eq(VocPaySaleDO::getUserId, userId);
            VocPaySaleDO vocPaySaleDO = vocPaySaleMapper.selectOne(vocPaySaleDOLambdaQueryWrapper);

            if (vocPaySaleDO.getItemType() == 1) {
                String input = vocPaySaleDO.getItemName();

                // 提取数字部分
                String numericPart = input.replaceAll("[^0-9]", "");

                if (!numericPart.isEmpty()) {
                    Long value = Long.parseLong(numericPart);
                    // 使用 value 进行后续操作
                    LambdaUpdateWrapper<UserVocBoundStatisticsDO> userVocBoundStatisticsDOLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
                    userVocBoundStatisticsDOLambdaUpdateWrapper.eq(UserVocBoundStatisticsDO::getUserId, userId).setSql("total=total+" + value).setSql("pay=pay+" + value);
                    userVocBoundStatisticsMapper.update(userVocBoundStatisticsDOLambdaUpdateWrapper);
                } else {
                    // 处理没有数字的情况
                    throw new IllegalArgumentException("输入字符串中未找到有效数字");
                }
            }

            if (vocPaySaleDO.getItemType() == 2) {
                System.out.println("2");
                String substring = vocPaySaleDO.getItemName().substring(2);
                String substring1 = vocPaySaleDO.getItemName().substring(5);
                LambdaUpdateWrapper<UserDO> userDOLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
                userDOLambdaUpdateWrapper.eq(UserDO::getId, userId).set(UserDO::getLevelName, substring).set(UserDO::getLevelValue,substring1)
                                .set(UserDO::getLevelDate, LocalDate.now());
                userMapper.update(userDOLambdaUpdateWrapper);
            }
            if (vocPaySaleDO.getItemType() == 3) {
                LambdaUpdateWrapper<UserDO> userDOLambdaUpdateWrapper1 = new LambdaUpdateWrapper<>();
                userDOLambdaUpdateWrapper1.eq(UserDO::getId, userId).set(UserDO::getHasSignCard, 1);
                userMapper.update(userDOLambdaUpdateWrapper1);
            }


            return "SUCCESS";
        }
        return "FALIES";


    }

    @Override
    public Integer queryTradeStatus(Long paySaleId) {
        System.out.println("query");
        if (paySaleId < 0) {
            return null;
        }
        LambdaQueryWrapper<VocPaySaleDO> vocPaySaleDOLambdaQueryWrapper = new LambdaQueryWrapper<>();
        vocPaySaleDOLambdaQueryWrapper.eq(VocPaySaleDO::getId, paySaleId);
        VocPaySaleDO vocPaySaleDO = vocPaySaleMapper.selectOne(vocPaySaleDOLambdaQueryWrapper);
        return vocPaySaleDO.getStatus();

    }

    @Override
    public PageDTO<VocPaySaleDTO> getPaySaleHistory(Long userId, PageRequest pageRequest) {
        if (pageRequest == null) {
            return null;

        }
        LambdaQueryWrapper<VocPaySaleDO> vocPaySaleDTOLambdaQueryWrapper = new LambdaQueryWrapper<>();
        vocPaySaleDTOLambdaQueryWrapper.eq(VocPaySaleDO::getUserId, userId);
        Long l = vocPaySaleMapper.selectCount(vocPaySaleDTOLambdaQueryWrapper);

        if (pageRequest.getPageNum() == null) {
            List<VocPaySaleDO> vocPaySaleDOS = vocPaySaleMapper.selectList(vocPaySaleDTOLambdaQueryWrapper);
            return payConverter.vocPaySalePage2PageDTO(vocPaySaleDOS, l);
        }
        Page<VocPaySaleDO> vocPaySaleDOPage = new Page<>(pageRequest.getPageNum(), pageRequest.getCount());
        List<VocPaySaleDO> records = vocPaySaleDOPage.getRecords();
        return payConverter.vocPaySalePage2PageDTO(records, vocPaySaleDOPage.getTotal());


    }


}
